//
//  SMMoneyHomeViewController.m
//  SaveMoney
//
//  Created by user on 2018/11/22.
//  Copyright © 2018年 Sunflower. All rights reserved.
//

#import "SMMoneyHomeViewController.h"

#import "SMBnnerTableViewCell.h"
#import "SMSaveMoneyTableViewCell.h"
#import "SMMenuListTableViewCell.h"
#import "SMMoneyChatTableViewCell.h"
#import "AdaptiveHeader.h"
#import "SMSaveMoneyView.h"
#import "NSAttributedString+YYText.h"
#import "SMMessageListViewController.h"

@interface SMMoneyHomeViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation SMMoneyHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self reload];
}

- (void)reload {
    _moneyModel = [SMMoneyModel findByPK:_moneyModel.id];
    [_tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return SBScaleNumber(200);
    } else if (indexPath.row == 1) {
        return SBScaleNumber(180);
    } else if (indexPath.row == 2) {
         return SBScaleNumber(100);
    } else {
         return SBScaleNumber(450);
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        SMBnnerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMBnnerTableViewCell" forIndexPath:indexPath];
        
        NSString *type;
        if (_moneyModel.saveMoneyType == SMFixation) {
            type = @"期间固定存钱";
        } else if (_moneyModel.saveMoneyType == SMFreedom) {
            type = @"期间不固定存钱";
        } else {
            type = @"无目标自由存钱";
        }
        [cell.bgImageView setImage:[UIImage base64ChangeImageWithEncode:_moneyModel.backImage]];
        cell.monryType.text = type;
        
        NSMutableAttributedString *total = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%ld",(long)_moneyModel.totalMoney]];
        [total yy_setFont:[UIFont systemFontOfSize:SBScaleNumber(14)] range:NSMakeRange(0, 1)];
        
        cell.totalMoneyLabel.attributedText = total;
        
        cell.saveMoneyLabel.text = [NSString stringWithFormat:@"已存：￥%ld",(long)_moneyModel.alreadyMoney];
        return cell;
        
    } else if (indexPath.row == 1) {
        SMSaveMoneyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMSaveMoneyTableViewCell" forIndexPath:indexPath];
        
        if (!_moneyModel.isSave) {
            [cell.saveMoneyButton setTitle:@"存款已够" forState:UIControlStateNormal];
            [cell.saveMoneyButton setBackgroundColor:[UIColor grayColor]];
            [cell.saveMoneyButton setUserInteractionEnabled:NO];
            
            cell.saveMessageLabel.text = @"恭喜！您已达目标~";
        } else {
            
            if ([self todayIsSave]) {
                [cell.saveMoneyButton setTitle:@"今日已存" forState:UIControlStateNormal];
                [cell.saveMoneyButton setBackgroundColor:[UIColor grayColor]];
                [cell.saveMoneyButton setUserInteractionEnabled:NO];
                
                cell.saveMessageLabel.text = @"今日已存，再接再厉！";
                
            } else {
                [cell.saveMoneyButton setTitle:@"存" forState:UIControlStateNormal];
                [cell.saveMoneyButton setUserInteractionEnabled:YES];
                
                if (_moneyModel.saveMoneyType == SMEverFreedom) {
                    cell.saveMessageLabel.text = [NSString stringWithFormat:@"您可以自由存入金额"];
                    
                } else if (_moneyModel.saveMoneyType == SMFreedom) {
                    NSMutableAttributedString *total = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"离目标金额还剩（￥%d）",_moneyModel.totalMoney-_moneyModel.alreadyMoney]];
                    [total yy_setColor:[UIColor blackColor] range:NSMakeRange(8, total.length-9)];
                    [total yy_setFont:[UIFont systemFontOfSize:SBScaleNumber(14)] range:NSMakeRange(8, 1)];
                    cell.saveMessageLabel.attributedText = total;
                    
                }  else {
                    NSMutableAttributedString *total = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"您今日还需要存（￥%ld）",(long)_moneyModel.everyDayMoney]];
                    [total yy_setColor:[UIColor blackColor] range:NSMakeRange(8, total.length-9)];
                    [total yy_setFont:[UIFont systemFontOfSize:SBScaleNumber(14)] range:NSMakeRange(8, 1)];
                    cell.saveMessageLabel.attributedText = total;
                }
            }
         
        }
        
        __weak typeof(self) weakSelf = self;
        cell.block = ^(UIButton * _Nonnull sender) {
            
            SMSaveMoneyView *view = [SMSaveMoneyView showViewWithView:weakSelf.view];
            
            if (weakSelf.moneyModel.saveMoneyType == SMEverFreedom || weakSelf.moneyModel.saveMoneyType == SMFreedom) {
                view.sendMoneyLabel.text = @"";
                [view.sendMoneyLabel setUserInteractionEnabled:YES];
            } else {
                [view.sendMoneyLabel setUserInteractionEnabled:NO];
                [view.sendMoneyLabel setBackgroundColor:[UIColor grayColor]];
                [view.sendMoneyLabel setTextColor:[UIColor whiteColor]];
                view.sendMoneyLabel.text = [NSString stringWithFormat:@"%ld",(long)weakSelf.moneyModel.everyDayMoney];
            }
            view.block = ^(UIButton * _Nonnull sender, NSInteger money, NSString * _Nonnull message) {
                
                weakSelf.moneyModel.alreadyMoney += money;
                
                NSInteger everDay = (weakSelf.moneyModel.totalMoney - weakSelf.moneyModel.alreadyMoney)/[self saveDay];
                weakSelf.moneyModel.everyDayMoney = everDay;
                
                if (weakSelf.moneyModel.saveMoneyType == SMEverFreedom) {
                    weakSelf.moneyModel.totalMoney = weakSelf.moneyModel.alreadyMoney;
                }
                
                [weakSelf.moneyModel update];
                
                SMSaveMoneyMessageModel *model = [[SMSaveMoneyMessageModel alloc] init];
                model.projectId = weakSelf.moneyModel.id;
                model.userKey = weakSelf.moneyModel.userKey;
                model.total = weakSelf.moneyModel.totalMoney;
                model.bitMoney = weakSelf.moneyModel.alreadyMoney;
                model.saveMoney = money;
                model.message = message;
                model.type = EverDaySave;
                model.costMoney = 0;
                model.creationTime = [NSString getNowTime];
                model.saveMoneyTitle = weakSelf.moneyModel.saveMoneyTitle;
                [model save];
                
                [weakSelf reload];
            };
            
        };
        
        return cell;
        
    } else if (indexPath.row == 2) {
        SMMenuListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMMenuListTableViewCell" forIndexPath:indexPath];
        cell.moneyModel = _moneyModel;
        __weak typeof(self) weakSelf = self;
        cell.block = ^(NSIndexPath * _Nonnull indexPath, UICollectionViewCell * _Nonnull cell) {
            
            
            if (indexPath.row == 0) {
                
                SMSaveMoneyView *view = [SMSaveMoneyView showViewWithView:weakSelf.view];
                [view.button setImage:[UIImage imageNamed:@"qukuan"] forState:UIControlStateNormal];
                view.titleLabel.text = @"支出";
                view.block = ^(UIButton * _Nonnull sender, NSInteger money, NSString * _Nonnull message) {
                    
                    if (money > weakSelf.moneyModel.alreadyMoney) {
                        [SVProgressHUD showErrorWithStatus:@"金额大于剩余金额"];
                        return ;
                    }
                    weakSelf.moneyModel.alreadyMoney -= money;
                    
                    NSInteger everDay = (weakSelf.moneyModel.totalMoney - weakSelf.moneyModel.alreadyMoney)/[self saveDay];
                    weakSelf.moneyModel.everyDayMoney = everDay;
                    
                    if (weakSelf.moneyModel.saveMoneyType == SMEverFreedom) {
                        weakSelf.moneyModel.totalMoney = weakSelf.moneyModel.alreadyMoney;
                    }
                    
                    [weakSelf.moneyModel update];
                    
                    SMSaveMoneyMessageModel *model = [[SMSaveMoneyMessageModel alloc] init];
                    model.projectId = weakSelf.moneyModel.id;
                    model.userKey = weakSelf.moneyModel.userKey;
                    model.total = weakSelf.moneyModel.totalMoney;
                    model.bitMoney = weakSelf.moneyModel.alreadyMoney;
                    model.saveMoney = 0;
                    model.message = message;
                    model.type = CostMoney;
                    model.costMoney = money;
                    model.creationTime = [NSString getNowTime];
                    model.saveMoneyTitle = weakSelf.moneyModel.saveMoneyTitle;
                    [model save];
                    
                    [weakSelf reload];
                };
                
            } else if (indexPath.row == 1) {
                
                if (!weakSelf.moneyModel.isSave) {
                    [SVProgressHUD showErrorWithStatus:@"以存够存款，无需再存"];
                    return ;
                }
                
                SMSaveMoneyView *view = [SMSaveMoneyView showViewWithView:weakSelf.view];
                
                view.block = ^(UIButton * _Nonnull sender, NSInteger money, NSString * _Nonnull message) {
                    
                    weakSelf.moneyModel.alreadyMoney += money;
                    
                    NSInteger everDay = (weakSelf.moneyModel.totalMoney - weakSelf.moneyModel.alreadyMoney)/[self saveDay];
                    weakSelf.moneyModel.everyDayMoney = everDay;
                    
                    if (weakSelf.moneyModel.saveMoneyType == SMEverFreedom) {
                        weakSelf.moneyModel.totalMoney = weakSelf.moneyModel.alreadyMoney;
                    }
                    
                    [weakSelf.moneyModel update];
                    
                    SMSaveMoneyMessageModel *model = [[SMSaveMoneyMessageModel alloc] init];
                    model.projectId = weakSelf.moneyModel.id;
                    model.userKey = weakSelf.moneyModel.userKey;
                    model.total = weakSelf.moneyModel.totalMoney;
                    model.bitMoney = weakSelf.moneyModel.alreadyMoney;
                    model.saveMoney = money;
                    model.message = message;
                    model.type = SaveMoney;
                    model.costMoney = 0;
                    model.creationTime = [NSString getNowTime];
                    model.saveMoneyTitle = weakSelf.moneyModel.saveMoneyTitle;
                    [model save];
                    
                    [weakSelf reload];
                };
            } else {
                
                SMMessageListViewController *vc = [[UIStoryboard storyboardWithName:@"SMHome" bundle:nil] instantiateViewControllerWithIdentifier:@"SMMessageListViewController"];
                vc.moneyModel = weakSelf.moneyModel;
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            }
        };
        
        return cell;
        
    } else {
        SMMoneyChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMMoneyChatTableViewCell" forIndexPath:indexPath];
        
//        NSDate *starDate = [NSString dateFromTimeStr:_moneyModel.creationTime];
//        NSArray *alldate = [starDate getAllDateWithDifferenceByDateCount:_moneyModel.saveMoneyDay];
        
        NSArray *proArray = [SMSaveMoneyMessageModel findByCriteria:[NSString stringWithFormat:@"Where userKey = '%@' And projectId = %d And type = 2",_moneyModel.userKey,_moneyModel.id]];
        NSMutableArray *dateArray = [[NSMutableArray alloc] init];
        for (SMSaveMoneyMessageModel *model in proArray) {
            NSDate *date = [NSString dateFromTimeStr:model.creationTime];
            [dateArray addObject:date];
        }
        
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (NSDate *obj in dateArray) {
            LXCalendarDayModel *model = [[LXCalendarDayModel alloc] init];
            model.year = obj.dateYear;
            model.month = obj.dateMonth;
            model.day = obj.dateDay;
            [array addObject:model];
        }
        cell.calenderView.saveDataArray = array;
        [cell.calenderView dealData];
        
        return cell;
    }
}


- (BOOL)todayIsSave {
    
    NSArray *proArray = [SMSaveMoneyMessageModel findByCriteria:[NSString stringWithFormat:@"Where userKey = '%@' And projectId = %d And type = 2",_moneyModel.userKey,_moneyModel.id]];
    NSString *time = [NSString getNowTime];
    for (SMSaveMoneyMessageModel *model in proArray) {
        if ([model.creationTime isEqualToString:time]) {
            return YES;
        }
    }
    
    
    return NO;
}

- (NSInteger)saveDay {
    NSArray *proArray = [SMSaveMoneyMessageModel findByCriteria:[NSString stringWithFormat:@"Where userKey = '%@' And saveMoneyTitle = '%@' And type = 2",_moneyModel.userKey,_moneyModel.saveMoneyTitle]];
    return proArray.count?proArray.count:_moneyModel.saveMoneyDay;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
